#include "../include/logical_pool.h"
#include "../include/conf_reader.h"
#include "../include/logical_handler.h"

logical_pool::logical_pool(){
    pool_size=std::atoi(conf_reader::get_conf_reader_instance()->get_value_from_key("logical_pool_size","3"));
    this->is_stop=false;
    for(int i=0;i<pool_size;++i){
        thread_vector.emplace_back([this](){
            
            while(1){
                std::unique_lock<std::mutex> u_l(this->mtx);
                this->cond_var.wait(u_l,[this](){
                    return this->is_stop==true||!this->task_queue.empty();  //不为空或想要停止，就往下走
                });
                if(this->is_stop==true){
                    break;
                }
                //那么拿到数据，执行即可
                auto item=this->task_queue.front();
                this->task_queue.pop();
                u_l.unlock();

                logical_handler::get_instance()->get_func_and_execute(item);
                

            }
        });
    }
}

void logical_pool::post_task(struct full_msg * msg)
{
    {
        std::lock_guard<std::mutex>l_g(mtx);
        this->task_queue.push(msg);
    }
    cond_var.notify_one();
    

}

logical_pool::~logical_pool()
{
    is_stop=true;
    cond_var.notify_all();
    for(auto &_thread_item:thread_vector){
        _thread_item.join();
    }
    while(!task_queue.empty()){
        //直接delete掉吧,不考虑执行完再结束
        delete task_queue.front();
        task_queue.pop();
    }
    

}
